package utils

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"errors"
	"fmt"
)

func DecryptMessage(cipherText string, key string) (string, error) {
	// Decode PEM encoded private key
	block, _ := pem.Decode([]byte(key))
	if block == nil || block.Type != "RSA PRIVATE KEY" {
		fmt.Println("1111")
		return "", errors.New("failed to decode PEM block containing private key")
	}

	// Parse the private key
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		fmt.Println("2222")
		return "", err
	}

	// Decode the base64 encoded ciphertext
	cipherBytes, err := base64.StdEncoding.DecodeString(cipherText)
	if err != nil {
		fmt.Println("3333")
		return "", err
	}

	// Decrypt the message
	label := []byte("")
	//plainText, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, priv, cipherBytes, label)
	plainText, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, priv, cipherBytes, label)
	if err != nil {
		fmt.Println("4444")
		return "", err
	}

	return string(plainText), nil
}
